from Simulinux.Core.Blocks.Gain import Gain
from Simulinux.Views.View import SELECT_COLOR
from Simulinux.Views.Blocks.GenericBlockView import *
from Simulinux.Views.Constants import MODE_NORMAL

class MathGainView(GenericBlockView):
    block_class = Gain
    def __init__(self, block, parent_view):
        GenericBlockView.__init__(self, block, parent_view)
        self.width = 40
        self.height = 40
        self._create_single_input_pin_view(0)
        self._create_single_output_pin_view(1)
        self.__builder = self._parent_view.get_ui_builder()
        self.__props_dialog = self.__builder.get_object("dialogPropertiesGain")
        self.__entry_name = self.__builder.get_object("entryGainName")
        self.__entry_amplitude = self.__builder.get_object("entryGainAmplitude")
    def draw(self, context):
        self.set_color(context)
        x_b, y_b, w, h = context.text_extents(self.block.name)[:4]
        text_y = self.block.posy - TEXT_VPADDING
        text_x = self.block.posx + self.width/2 - w/2 + x_b
        context.move_to(text_x, text_y)
        context.show_text(self.block.name)
        context.rectangle(self.block.posx, self.block.posy, self.width, self.height)
        #k string inside the rectangle
        context.set_font_size(20)
        x_b, y_b, w, h = context.text_extents("k")[:4]
        k_y = self.block.posy + self.height/2 + h/2
        k_x = self.block.posx + self.width/2 - w/2 + x_b
        context.move_to(k_x, k_y)
        context.show_text("k")
        context.set_font_size(10)
        self._draw_pins(context)
        context.stroke()
    def edit_properties(self):
        #@todo: Add key press events: ESC (close dialog), ENTER (confirm changes)
        #@todo: Validate data before setting 
        self.__entry_name.set_text(self.block.name)
        self.__entry_amplitude.set_text(str(self.block.amplitude))
        self.__props_dialog.set_default_response(1)
        #self.__entry_name.grab_focus()
        response = self.__props_dialog.run()
        if response == 1: #Change properties
            self.block.name = self.__entry_name.get_text()
            self.block.amplitude = self.__entry_amplitude.get_text()
        self.__props_dialog.hide()
        self._parent_view.switch_mode(MODE_NORMAL)

if __name__=="__main__":
    gain = Gain()
    view = MathGainView(gain)
    view.generate_pixmap("math_gain")